"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * @author: HZWei
 * @date: 2024/7/14
 * @desc:
 *
 * node.js 执行ts文件, 用tsc编译将ts文件编译成js文件，然后通过node test.js 执行脚本
 * tsc test.ts
 * node test.js
 */
var fs = require("fs");
var fs_1 = require("fs");
var path_1 = require("path");
var handlebars_1 = require("handlebars");
var json5_1 = require("json5");
var model_1 = require("./src/model");
function getFilesInDir(dirPath) {
    var files = new Array();
    function find(currentDir) {
        var contents = (0, fs_1.readdirSync)(currentDir, { withFileTypes: true });
        contents.forEach(function (value, index) {
            // 文件目录路径 + 文件名称  = 文件路径
            var filePath = path_1.join(currentDir, value.name);
            if (value.isDirectory()) {
                find(filePath);
            }
            else if (value.isFile()) {
                files.push(filePath);
            }
        });
    }
    find(dirPath);
    console.log(files);
    return files;
}
// const  files = getFilesInDir('./src')
function generateFile(dir, fileName) {
    // 读取模板文件
    var source = fs.readFileSync('template2.txt', 'utf8');
    // 编译模版
    var template = handlebars_1.default.compile(source);
    // 提供数据 并渲染模版
    var content = {
        title: "我是标题",
        content: "我是内容"
    };
    var html = template(content);
    console.log(html);
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, { recursive: true });
    }
    (0, fs_1.writeFileSync)("".concat(dir).concat(fileName), html);
}
// 注意：目录必须带反斜杆的
// generateFile('./src/test/','test2.html')
// const importPath = path.relative(`${config.modulePath}/${config.builderDir}`, sourcePath).replaceAll("\\", "/").replaceAll(".ets", "");
var config = new model_1.PluginConfig();
var routeMap = new model_1.RouteMap();
config.scanDir = 'src/main/ets/';
config.generatedDir = 'src/main/ets/generated/';
config.indexDir = __dirname;
config.moduleJsonPath = 'src/main/ets/module.json5';
config.routerMapPath = 'src/main/ets/resources/base/profile/route_map.json';
function generateBuilderRegisterFile(dir, fileName) {
    var source = fs.readFileSync('builderRegister2.txt', 'utf8');
    var template = handlebars_1.default.compile(source);
    var content = {
        pageList: getPageInfos()
    };
    var ts = template(content);
    console.log(ts);
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, { recursive: true });
    }
    (0, fs_1.writeFileSync)("".concat(dir).concat(fileName), ts);
    generateRouterMap(content.pageList);
}
function generateRouterMap(pageInfos) {
    var routeMap = new model_1.RouteMap();
    routeMap.routerMap = pageInfos.map(function (item) {
        var route = new model_1.RouteInfo();
        route.name = item.pageName;
        route.pageSourceFile = item.absolutePath.replace(/\\/g, '/');
        route.buildFunction = item.buildFunctionName;
        return route;
    });
    (0, fs_1.writeFileSync)(config.routerMapPath, JSON.stringify(routeMap, null, 2), { encoding: "utf8" });
}
function getPageInfos() {
    // 模拟测试
    var pagePaths = getFilesInDir(config.scanDir).filter(function (item) { return item.includes("-page.ts"); });
    return pagePaths.map(function (filePath) {
        // 文件名：不包括后缀
        var fileName = path_1.basename(filePath, path_1.extname(filePath));
        var pageName = convert(fileName);
        // 将绝对路径转换成相对路径
        var importPath = path_1.relative(config.generatedDir, filePath.substring(0, filePath.lastIndexOf('.'))).replace(/\\/g, '/');
        return {
            pageName: pageName,
            importPath: importPath,
            absolutePath: filePath,
            buildFunctionName: "".concat(pageName, "Builder")
        };
    });
}
function convert(str) {
    return str.replace(/(?:^|-)\w/g, function (match) { return match.toUpperCase().replace(/-/, ''); });
}
function generateIndexFile(dir) {
    var indexPath = "".concat(config.indexDir, "/Index2.ts");
    var builderRegisterPath = path_1.join(config.generatedDir, 'builderRegister.ts');
    var importPath = path_1.relative(dir, builderRegisterPath.substring(0, builderRegisterPath.lastIndexOf('.'))).replace(/\\/g, '/');
    var data = "export * from './".concat(importPath, "'");
    if (!fs.existsSync(indexPath)) {
        fs.writeFileSync(indexPath, data);
        return;
    }
    var content = fs.readFileSync(indexPath, { encoding: "utf8" });
    var lines = content.split('\n');
    var target = lines.find(function (item) { return item === data; });
    if (!target) {
        lines.push(data);
        fs.writeFileSync(indexPath, lines.join('\n'), { encoding: "utf8" });
    }
}
function checkIfModuleRouterMapConfig() {
    // 检查 module.json5文件是否配置路由表文件
    if (!fs.existsSync(config.moduleJsonPath))
        return;
    var content = (0, fs_1.readFileSync)(config.moduleJsonPath, "utf8");
    var module = json5_1.default.parse(content);
    if (module.module.routerMap)
        return;
    module.module.routerMap = "$profile:route_map";
    fs.writeFileSync(config.moduleJsonPath, JSON.stringify(module, null, 2), { encoding: "utf8" });
}
generateBuilderRegisterFile(config.generatedDir, 'builderRegister.ts');
generateIndexFile(config.indexDir);
checkIfModuleRouterMapConfig();
